package com.xbongbong.parent.abstracts;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.model.OuterLinkModel;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.DataDetailPojo;
import com.xbongbong.paas.pojo.DetailTabPojo;
import com.xbongbong.paas.pojo.DetailTitlePojo;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.HandelDetailPojo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.WorkFlowPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.help.CommonPermissionHelp;
import com.xbongbong.parent.interfaces.BusinessDetailTopInfoService;
import com.xbongbong.pro.appdetail.pojo.MobileDetailMoneyItemPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailSpecialInfoPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailStatusBlockPojo;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.domain.entity.LabelEntity;
import com.xbongbong.pro.domain.entity.PersonLabelEntity;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.form.pojo.TopPermissionsPoJo;
import com.xbongbong.pro.formdata.pojo.dto.FormDataDetailDTO;
import com.xbongbong.pro.formdata.pojo.vo.FormDataDetailVO;
import com.xbongbong.pro.formdata.pojo.vo.MobileFormCommonDetailVO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.pro.label.pojo.LabelPojo;
import com.xbongbong.pro.permission.pojo.dto.VerifyViewPermissionDTO;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.enums.BusinessDetailTabEnum;
import com.xbongbong.saas.enums.DetailTabEnum;
import com.xbongbong.saas.enums.OuterLinkTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.enums.dictionary.PaymentStatusEnum;
import com.xbongbong.saas.model.DataDictionaryModel;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.saas.model.PersonLabelModel;
import com.xbongbong.saas.model.SaleStageModel;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.help.ProPermissionHelp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @author 吴峰
 * @date 2021/12/30 14:07
 */
@Component
public abstract class AbstractBusinessDetailTopInfoService<T, D> extends AbstractParentBusinessDetailService<T, D> implements BusinessDetailTopInfoService<T, D> {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractBusinessDetailTopInfoService.class);

    @Resource
    private PackageHelp packageHelp;
    @Resource
    private OuterLinkModel outerLinkModel;
    @Resource
    private PersonLabelModel personLabelModel;
    @Resource
    private DataDictionaryModel dataDictionaryModel;
    @Resource
    private LabelModel labelModel;
    @Resource
    private SaleStageModel saleStageModel;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    protected CommonPermissionHelp commonPermissionHelp;
    @Resource
    protected ProPermissionHelp proPermissionHelp;

    @Override
    public FormDataDetailVO getDetail(FormDataDetailDTO formDataDetailDTO) throws XbbException {
        try {
            String corpid = formDataDetailDTO.getCorpid();
            Integer distributorMark = formDataDetailDTO.getDistributorMark();
            // 根据id获取数据
            D formData = getData(formDataDetailDTO.getBusinessType(), formDataDetailDTO.getSubBusinessType(), formDataDetailDTO.getSaasMark(), corpid, formDataDetailDTO.getDataId(), null);
            // 根据查到的数据，然后再根据数据中的表单id，获取表单实体
            T form = getForm(formDataDetailDTO, formData, corpid);


            // 获取字段
            List<FieldAttrEntity> explainList = getExplainList(form, corpid);
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(formDataDetailDTO, handlerExplainDTO, false);

            // 解析字段
            HandlerExplainVO handlerExplainVO = handleExplain(explainList, form, formData, handlerExplainDTO);
            PaasFormDataEntityExt tempData = (PaasFormDataEntityExt) formData;
            tempData.getData().put(FieldTypeEnum.OWNERID.getAlias(), handlerExplainVO.getOwnerId());
            tempData.getData().put(FieldTypeEnum.COUSERID.getAlias(), handlerExplainVO.getCoUserId());
            D paasFormDataEntityExt = (D) tempData;
            // 校验权限
            checkPermission(form, paasFormDataEntityExt, formDataDetailDTO.getLoginUser(), formDataDetailDTO.getSubBusinessType());
            explainList = handlerExplainVO.getHeadList();
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMapByList(explainList);
            HandelDetailPojo handelDetailPojo = new HandelDetailPojo(distributorMark, formDataDetailDTO.getBusinessType(), null, new ArrayList<>(), formDataDetailDTO.getLoginUser());

            // 详情页头部按钮
            List<ButtonPojo> buttonList = handleDetailButton(formDataDetailDTO, handelDetailPojo, paasFormDataEntityExt, explainMap);
            // 返回关联新建
            List<WorkFlowPojo> workflowList = webHandleDetailWorkFlow(handelDetailPojo, form, formData);

            // 解析数据
            JSONObject data = analysisData(formData, handlerExplainDTO, handlerExplainVO);
            // 获取摘要
            JSONArray summaryList = getSecondTitleList(formDataDetailDTO, formData, form, explainList, explainMap,  data);
            // 获取标签
            JSONArray labelList = getTagList(formDataDetailDTO, formData, form, explainList, explainMap, data);
            // 处理详情页特殊返回，bom版本，跨月，分数，拨打电话等
            DataDetailPojo dataDetailPojo = handleDetailData(formDataDetailDTO.getBusinessType(), formData, formDataDetailDTO.getUserId(), handlerExplainDTO);

            // 印章，是否关注
            DetailTitlePojo detailTitlePojo = handleDetailFocus(formDataDetailDTO, formDataDetailDTO.getBusinessType(), formData, formDataDetailDTO.getUserId());
            // 获取标题
            String title = getTitle(formDataDetailDTO, formData, form, explainList, explainMap, data);
            detailTitlePojo.setName(title);

            FormDataDetailVO formDataDetailVO = new FormDataDetailVO();
            // 标签编辑快捷字段
            String label = dealWebDetailLabelListLocation(formDataDetailDTO, form, labelList, paasFormDataEntityExt, explainMap);
            formDataDetailVO.setLabelEditAttr(label);
            // 获取tab列表
            List<DetailTabPojo> detailTabList = handleDetailTab(handelDetailPojo, form, formData, explainMap, handlerExplainVO, handlerExplainDTO);

            //未开启工作流的公司不能查看审批记录
            boolean isOpenWorkflow = commonHelp.isOpenWorkFlow(corpid);
            if(!isOpenWorkflow){
                detailTabList.removeIf(v -> Objects.equals(v.getAttr(), DetailTabEnum.APPROVAL_RECORDS.getKey()));
            }

            // 将按钮，标题，摘要，标签，关联新建放入dataDetailPojo中
            DataDetailPojo.setDataDetailPOJO(dataDetailPojo, formDataDetailDTO.getLoginUser(), buttonList, detailTitlePojo, summaryList, labelList, workflowList);
            formDataDetailVO.setTab(detailTabList);
            formDataDetailVO.setHead(dataDetailPojo);
            // 将表单信息放入vo中
            setFormEntity(formDataDetailDTO, form, formDataDetailVO);

            return formDataDetailVO;
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("AbstractBusinessDetailTopInfoService.detail报错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public MobileFormCommonDetailVO getMobileDetail(FormDataDetailDTO formDataDetailDTO) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        Integer distributorMark = formDataDetailDTO.getDistributorMark();
        Long dataId = formDataDetailDTO.getDataId();
        Integer subBusinessType = formDataDetailDTO.getSubBusinessType();
        Integer businessType = formDataDetailDTO.getBusinessType();
        String userId = formDataDetailDTO.getUserId();
        UserVO loginUser = formDataDetailDTO.getLoginUser();
        // 根据id获取数据
        D formData = getData(formDataDetailDTO.getBusinessType(), formDataDetailDTO.getSubBusinessType(), formDataDetailDTO.getSaasMark(), corpid, formDataDetailDTO.getDataId(), null);
        // 根据查到的数据，然后再根据数据中的表单id，获取表单实体
        T form = getForm(formDataDetailDTO, formData, corpid);

        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(formDataDetailDTO, handlerExplainDTO, false);

        // 获取字段
        List<FieldAttrEntity> explainList = getExplainList(form, corpid);
        // 解析字段
        HandlerExplainVO handlerExplainVO = handleExplain(explainList, form, formData, handlerExplainDTO);
        PaasFormDataEntityExt paasFormDataEntityExt = (PaasFormDataEntityExt) formData;
        paasFormDataEntityExt.getData().put(FieldTypeEnum.OWNERID.getAlias(), handlerExplainVO.getOwnerId());
        paasFormDataEntityExt.getData().put(FieldTypeEnum.COUSERID.getAlias(), handlerExplainVO.getCoUserId());
        // 校验权限
        checkPermission(form, (D) paasFormDataEntityExt, formDataDetailDTO.getLoginUser(), formDataDetailDTO.getBusinessType());

        explainList = handlerExplainVO.getHeadList();
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMapByList(explainList);
        // 解析数据
        JSONObject data = analysisData(formData, handlerExplainDTO, handlerExplainVO);

        MobileFormCommonDetailVO mobileFormCommonDetailVO = new MobileFormCommonDetailVO();
        List<MobileDetailMoneyItemPojo> moneyInfoList = getMobileDetailMoneyInfo(distributorMark,  corpid, userId, businessType, subBusinessType, dataId, data, explainMap, loginUser, formData);
        mobileFormCommonDetailVO.setMoneyInfo(moneyInfoList);
        // 获取移动端详情基本信息中的中部信息
        JSONArray bottomBlockInfo = getBottomBlockInfo(corpid, userId, businessType, form, dataId, data, explainMap, formData, handlerExplainDTO);
        mobileFormCommonDetailVO.setBottomBlockInfo(bottomBlockInfo);
        // 移动端详情基础信息右侧显示的特殊信息
        MobileDetailSpecialInfoPojo specialInfoPojo = getMobileDetailSpecialInfo(formDataDetailDTO, formData,explainMap);
        mobileFormCommonDetailVO.setRightSpecialInfo(specialInfoPojo);
        // 摘要
        List<SummaryDataPoJo> summaryList = getSummaryList(formDataDetailDTO, formData, form, explainList, explainMap, data);
        mobileFormCommonDetailVO.setSummaryList(summaryList);
        // 解析标签
        List<SummaryDataPoJo> labelsList = getLabelList(formDataDetailDTO, formData, form, explainList, explainMap, data);
        getLabelList(labelsList, corpid, businessType, dataId, userId);
        mobileFormCommonDetailVO.setLabelsList(labelsList);
        // 标题
        List<FormTitlePoJo> formTitleList = getTitleList(formDataDetailDTO, formData, form, explainList, explainMap, data);
        mobileFormCommonDetailVO.setTitleList(formTitleList);
        HandelDetailPojo handelDetailPojo = new HandelDetailPojo(distributorMark, formDataDetailDTO.getBusinessType(), null, new ArrayList<>(), formDataDetailDTO.getLoginUser());

        List<DetailTabPojo> tabList = handleDetailTab(handelDetailPojo, form, formData, explainMap, handlerExplainVO, handlerExplainDTO);

        //未开启工作流的公司不能查看审批记录
        boolean isOpenWorkflow = commonHelp.isOpenWorkFlow(corpid);
        if(!isOpenWorkflow){
            tabList.removeIf(v -> Objects.equals(v.getAttr(), DetailTabEnum.APPROVAL_HISTORY.getKey()) || Objects.equals(v.getAttr(), DetailTabEnum.APPROVAL_PROCESS.getKey()));
        }
        mobileFormCommonDetailVO.setTabList(tabList);
        JSONObject returnJson = returnSaasObject(corpid, businessType, loginUser, formData);
        returnJson = returnJson == null ? new JSONObject() : returnJson;
        mobileFormCommonDetailVO.setSaasObj(returnJson);
        // 返回按钮以及关联新建
        List<TopPermissionsPoJo> list = dingtalkHandleDetailWorkFlow(handelDetailPojo, form, (D) paasFormDataEntityExt, explainMap);
        //有团队的业务这边需要有权限的判断
        removeEditButtom(formDataDetailDTO, list, paasFormDataEntityExt, explainMap);
        // 获取移动端详情页底部操作按钮
        List<TopPermissionsPoJo> bottomOperationList = getMobileDetailBottomOperation(handelDetailPojo, form, formData, handlerExplainDTO, explainMap);
        mobileFormCommonDetailVO.setBottomOperation(bottomOperationList);

        // 标签编辑快捷字段
        String label = dealAppDetailLabelListLocation(formDataDetailDTO, form, labelsList, formData, explainMap);
        mobileFormCommonDetailVO.setLabelEditAttr(label);
        //移除校验格式化数据
        commonPermissionHelp.removeConvertedData(data);
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
            // todo 这里需要和前端一起改一下
            mobileFormCommonDetailVO.setTab(tabList);
        }
        returnVO(form, formData, mobileFormCommonDetailVO, userId);

        mobileFormCommonDetailVO.setTopPermissions(list);
        mobileFormCommonDetailVO.setData(data);
        return mobileFormCommonDetailVO;
    }

    /**
     * 需要根据当前人的可编辑权限去判断需不需要移除
     *
     * @param formDataDetailDTO
     * @param buttonPojoList
     * @param paasFormDataEntityExt
     * @param explainMap
     */
    public void removeEditButtom(FormDataDetailDTO formDataDetailDTO, List<TopPermissionsPoJo> buttonPojoList, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        Integer businessType = formDataDetailDTO.getBusinessType();
        UserVO loginUser = formDataDetailDTO.getLoginUser();
        //工单业务不处理
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
            return;
        }
        if (CollectionsUtil.isNotEmpty(buttonPojoList)) {
            VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO(loginUser, paasFormDataEntityExt);
            boolean perTag = commonPermissionHelp.checkEditPermissionWithoutShareEdit(formDataDetailDTO, verifyViewPermissionDTO, explainMap);
            if (!perTag) {
                Iterator<TopPermissionsPoJo> buttonPojoIterator =  buttonPojoList.iterator();
                while (buttonPojoIterator.hasNext()) {
                    TopPermissionsPoJo topPermissionsPoJo = buttonPojoIterator.next();
                    if (Objects.equals(SaasButtonEnum.EDIT.getAttr(), topPermissionsPoJo.getAttr())) {
                        buttonPojoIterator.remove();
                    }
                }
            }
        }
    }

    protected void setFormEntity(FormDataDetailDTO formDataDetailDTO, T form, FormDataDetailVO formDataDetailVO) {
        if (form instanceof PaasFormEntityExt) {
            formDataDetailVO.setPaasFormEntityExt((PaasFormEntityExt) form);
        } else {
            // 工单
            WorkOrderFormEntity workOrderFormEntity = (WorkOrderFormEntity) form;
            PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
            BeanUtil.copyProperties(workOrderFormEntity, paasFormEntityExt);
            paasFormEntityExt.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            paasFormEntityExt.setSaasMark(SaasMarkEnum.SAAS.getCode());
            formDataDetailVO.setPaasFormEntityExt(paasFormEntityExt);
        }
    }

    @Override
    public DetailTitlePojo handleDetailFocus(FormDataDetailDTO formDataDetailDTO, Integer businessType, D paasFormDataEntityExt, String userId) throws XbbException {
        return new DetailTitlePojo();
    }
    /**
     * 详情页是否有外链分享按钮
     * @param corpid
     * @param formId
     * @return void
     * @author 吴峰
     * @date 2022/2/14 17:01
     * @throws XbbException       
     */
    protected Integer setOuterLinkShare(String corpid, Long formId) throws XbbException {
        //校验套餐类型
        Integer feeType = packageHelp.getFeeType(corpid);
        if (!Objects.equals(feeType, PackageTypeEnum.STANDARD.getType())){
            boolean hasOuterLinkShare = outerLinkModel.checkOuterLinkEnable(formId, OuterLinkTypeEnum.SHARE.getCode(), corpid);
            return hasOuterLinkShare ? BasicConstant.ONE : BasicConstant.ZERO;
        }
        return 0;
    }

    protected JSONArray getSecondTitleList(List<SummaryDataPoJo> summaryList, JSONObject data, String corpid, Long formId) {
        JSONArray secondTitle = new JSONArray();
        // 科学计数
        String regx = "^((-?\\\\d+.?\\\\d*)[Ee]{1}(-?\\\\d+))$";
        Pattern pattern = Pattern.compile(regx);
        for (SummaryDataPoJo pojo : summaryList) {
            List<Object> list = CollectionsUtil.isEmpty(pojo.getValue()) ? new ArrayList<>() : pojo.getValue();
            if (list.size() > 0) {
                if (list.get(0) == null) {
                    list = new ArrayList<>();
                }
            }
            if (list.size() == 1 && list.get(0) instanceof Number) {
                JSONObject jsonObject = getSecondTitle(pojo, list.get(0), data, corpid, formId);
                secondTitle.add(jsonObject);
            } else {
                String value = "";
                StringBuilder stringBuilder1 = new StringBuilder();
                // 科学计数
                //String regx = "^((-?\\\\d+.?\\\\d*)[Ee]{1}(-?\\\\d+))$";
                //Pattern pattern = Pattern.compile(regx);
                for (Object object1 : list) {
                    boolean isNumber = pattern.matcher(object1.toString()).matches();
                    if (isNumber) {
                        try {
                            BigDecimal b = new BigDecimal(String.valueOf(object1));
                            object1 = b.stripTrailingZeros().toPlainString();
                        } catch (Exception e) {
                            LOG.error("科学计数异常：" + object1);
                        }
                    }
                    if (object1 instanceof ReturnUserAndDepartmentPojo) {
                        object1 = ((ReturnUserAndDepartmentPojo) object1).getName();
                    }
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(object1.toString());
                    String s = stringBuilder.toString() + "、";
                    stringBuilder1.append(s);
                }
                value = stringBuilder1.toString();
                if (value.length() > 0) {
                    value = value.substring(0, value.length() - 1);
                }
                JSONObject jsonObject = getSecondTitle(pojo, value, data, corpid, formId);
                secondTitle.add(jsonObject);
            }
        }
         return secondTitle;
    }

    @Override
    public JSONObject getSecondTitle(SummaryDataPoJo pojo, Object value, JSONObject data, String corpid, Long formId) {
        //负责人isTeam为true前端需要
        if (Objects.equals(pojo.getAttrName(), WorkOrderEnum.OWNER_ID.getAttrName()) || Objects.equals(pojo.getAttrName(), WorkOrderEnum.COUSERID.getAttrName())) {
            return ExplainUtil.getSecondTitleObj(true, pojo.getAttrName(), value);
        } else {
            return ExplainUtil.getSecondTitleObj(false, pojo.getAttrName(), value);
        }
    }

    protected JSONArray getTags(List<SummaryDataPoJo> labelsList, String corpid, Integer businessType, Long dataId, String userId) {
        JSONArray tags = new JSONArray();
        for (SummaryDataPoJo pojo : labelsList) {
            JSONObject object = new JSONObject();
            List<Object> list = CollectionsUtil.isEmpty(pojo.getValue()) ? new ArrayList<>() : pojo.getValue();
            if (Objects.equals(pojo.getFieldType(), FieldTypeEnum.LABEL.getType())){

                for (Object o : list) {
                    JSONObject object1 = JSON.parseObject(JSON.toJSONString(o));
                    object1.put("value", o);
                    if (Objects.equals(1, object1.getInteger("tabelType"))) {
                        continue;
                    }
                    object1.put("type", "label");
                    tags.add(object1);
                }
                //个人标签tags展示
                PersonLabelEntity personLabelEntity = personLabelModel.getPersonLabelByRefType(corpid, businessType, dataId, userId);
                if (Objects.nonNull(personLabelEntity)) {
                    JSONArray labelNameArray = personLabelEntity.getLabelName();
                    if (labelNameArray !=null && labelNameArray.size() > 0) {
                        JSONObject object1 = new JSONObject();
                        object1.put("value", personLabelEntity);
                        object1.put("type", "personLabel");
                        tags.add(object1);
                    }
                }
                continue;
            }
            String value = "";
            for (Object object1 : list) {
                value = object1.toString() + "-";
            }
            if (StringUtil.isNotEmpty(value)) {
                value = value.substring(0, value.length() - 1);
            }
            if (!Objects.equals(value, "")) {
                object.put("value", value);
                object.put("type", "normal");
                tags.add(object);
            }
        }
        return tags;
    }

    protected void getLabelList(List<SummaryDataPoJo> labelsList, String corpid, Integer businessType, Long dataId, String userId) {
        for (SummaryDataPoJo summaryDataPoJo : labelsList) {
            List<Object> list = summaryDataPoJo.getValue();
            if (Objects.equals(summaryDataPoJo.getFieldType(), FieldTypeEnum.LABEL.getType())) {
                JSONArray tags = new JSONArray();
                if (CollectionsUtil.isNotEmpty(list)) {
                    for (Object o : list) {
                        if (Objects.isNull(o)){
                            continue;
                        }
                        JSONObject object1 = JSON.parseObject(JSON.toJSONString(o));
                        object1.put("value", o);
                        if (Objects.equals(1, object1.getInteger("tabelType"))) {
                            continue;
                        }
                        object1.put("type", "label");
                        tags.add(object1);
                    }
                }
                //个人标签tags展示
                PersonLabelEntity personLabelEntity = personLabelModel.getPersonLabelByRefType(corpid, businessType, dataId, userId);
                if (Objects.nonNull(personLabelEntity)) {
                    JSONArray labelNameArray = personLabelEntity.getLabelName();
                    if (labelNameArray !=null && labelNameArray.size() > 0) {
                        JSONObject object1 = new JSONObject();
                        object1.put("type", "personLabel");
                        object1.put("value", personLabelEntity);
                        tags.add(object1);
                    }
                }
                summaryDataPoJo.setValue(tags);
                continue;
            }
        }

    }


    /**
     * 获取移动端详情状态区块信息
     *
     * @param corpid         公司id
     * @param data           数据
     * @param dictionaryEnum 数据字典项
     * @param dictionaryAttr 数据字典项对应的attr
     * @return MobileDetailStatusBlockPojo
     * @author GuoJun.HU
     * @date 2019/4/9 16:14
     * @since V1.0
     */
    protected MobileDetailStatusBlockPojo getMobileDetailStatusBlockPojo(String corpid, JSONObject data,
                                                                       DictionaryEnum dictionaryEnum, String dictionaryAttr, Integer editable) throws XbbException {
        List<ItemPoJo> itemPoJoList = dataDictionaryModel.getDictionaryList4Saas(dictionaryEnum, corpid, null);
        String currentCustomerStatus = FastJsonHelper.getStringOrDefaultFromFormData(data, dictionaryAttr, "");
        itemPoJoList.forEach(itemPoJo -> {
            if (Objects.equals(itemPoJo.getValue(), currentCustomerStatus)) {
                itemPoJo.setChecked(true);
            }
        });
        MobileDetailStatusBlockPojo statusBlockPojo = new MobileDetailStatusBlockPojo();
        statusBlockPojo.setEditable(editable);
        statusBlockPojo.setOptions(itemPoJoList);
        return statusBlockPojo;
    }

    /**
     * 特殊数据转换
     * @param corpid
     * @param summaryList
     * @param businessType
     * @param data
     * @param formId
     * @throws XbbException
     */
    protected void specialTransferKeyToShowValue(String corpid, List<SummaryDataPoJo> summaryList, Integer businessType, JSONObject data, Long formId) throws XbbException{
        //方便前端显示，把负责人拼接成一个
        for (SummaryDataPoJo poJo : summaryList) {
            if (Objects.equals(poJo.getAttr(), "ownerId") || Objects.equals(poJo.getAttrName(), I18nMessageUtil.getMessage(CommonConstant.COLLABORATOR))) {
                List<Object> value = poJo.getValue();
                if (value.size() > 0) {
                    String userName = "";
                    List<Object> list = new ArrayList<>();
                    StringBuilder stringBuilder1 = new StringBuilder();
                    for (Object object : value) {
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.append(object.toString());
                        String s = stringBuilder.toString() + "、";
                        stringBuilder1.append(s);
                    }
                    userName = stringBuilder1.toString();
                    if (userName.length() > 0) {
                        userName = userName.substring(0,userName.length()-1);
                    }
                    list.add(userName);
                    poJo.setValue(list);
                }
            }
            // // 标签设置
            if (Objects.equals(poJo.getFieldType(), FieldTypeEnum.LABEL.getType())){
                JSONArray jsonArray = data.getJSONArray(poJo.getAttr());
                if(Objects.nonNull(jsonArray) && CollectionsUtil.isNotEmpty(jsonArray)){
                    List<Long> longs = new ArrayList<>();
                    try {
                        List<LabelPojo> labelPojos = JSON.parseArray(jsonArray.toJSONString(), LabelPojo.class);
                        for (LabelPojo item : labelPojos) {
                            if (Objects.isNull(item.getTabelType()) || Objects.equals(item.getTabelType(),BasicConstant.ZERO)) {
                                longs.add(item.getId());
                            }
                        }
                    } catch (Exception e) {
                        longs = JSON.parseArray(jsonArray.toJSONString(), Long.class);
                    }
                    List<Object> value = new ArrayList<>();
                    if (longs != null && longs.size() > 0) {
                        List<LabelEntity> byLabelIds = labelModel.getByLabelIds(longs, corpid);
                        byLabelIds.forEach(item ->value.add(item.getName()));
                    }
                    poJo.setValue(value);
                }
            }
        }
        // SaaS的数据字典需要特殊处理：将存储的key转成用于显示的value
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        switch (redundantTemplateTypeEnum) {
            case PAYMENT:
                /**
                 * 资金改造一期，需要处理移动端详情页面的预计回款日期标红
                 * (预计回款日期大于等于今日的还未回款或部分回款的应收款)
                 * @author chenshan
                 * @Date 2019-11-06 13:53
                 */
                String status = FastJsonHelper.getStringOrDefaultFromFormData(data, PaymentEnum.STATUS.getAttr(), PaymentStatusEnum.UN_RECEIVABLES.getAlias());
                if ( Objects.equals(status, PaymentStatusEnum.UN_RECEIVABLES.getCode()) || Objects.equals(status, PaymentStatusEnum.PARTIAL_RECEIPTS.getCode()) ) {
                    for ( SummaryDataPoJo summaryDataPoJo : summaryList ) {
                        String attr = summaryDataPoJo.getAttr();
                        if ( Objects.equals(attr, PaymentEnum.ESTIMATE_TIME.getAttr()) ) {
                            List<Object> valueList = summaryDataPoJo.getValue();
                            if ( valueList.isEmpty() ) {
                                break;
                            }
                            String valueKey = (String) valueList.get(0);
                            Long estimate = DateTimeUtil.getInt(valueKey, DateTimeUtil.SDFDate);
                            if ( estimate < DateTimeUtil.getTodayInt() ) {
                                summaryDataPoJo.setStatus("delay");
                            }
                            break;
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 如果菜单名字改变,修改相应的表单名字
     * @param paasBusinessTypeToName
     * @param tabEnum
     * @param detailTabPojo
     */
    protected void changeTabEnumName(Map<Integer, String> paasBusinessTypeToName, BusinessDetailTabEnum tabEnum, DetailTabPojo detailTabPojo) {
        if (tabEnum.getFormBusinessType() != 0
                && Objects.nonNull(paasBusinessTypeToName.get(tabEnum.getFormBusinessType()))
                && !Objects.equals(paasBusinessTypeToName.get(tabEnum.getFormBusinessType()), XbbRefTypeEnum.getByCode(tabEnum.getFormBusinessType()).getName())) {
            detailTabPojo.setName(paasBusinessTypeToName.get(tabEnum.getFormBusinessType()));
        }
    }


    /**
     * 团队成员需求，要求只有负责人、协同人字段同时存在并且启用的情况下才会显示团队tab栏
     *重构前来自 -> com.xbongbong.saas.help.ProDetailHandlerHelp#handleTeamTab(java.util.List, java.util.Map)
     * @param tabPojoList 详情需要展示的一些tab栏列表
     * @param explainMap 表单解释
     */
    protected void handleTeamTab(List<DetailTabPojo> tabPojoList,  Map<String, FieldAttrEntity> explainMap) {
        //因为现在只有负责人、协同人字段同时开启，这时候详情tab栏才显示负责团队tab,团队成员需求提出的
        if (CollectionsUtil.isNotEmpty(tabPojoList)) {
            Iterator<DetailTabPojo> detailTabPojoIterator = tabPojoList.iterator();
            while (detailTabPojoIterator.hasNext()) {
                DetailTabPojo detailTabPojo =  detailTabPojoIterator.next();
                if (Objects.equals(detailTabPojo.getKey(), DetailTabEnum.SALE_TEAM.getKey())) {
                    FieldAttrEntity ownerIdFieldAttr = explainMap.get(FieldTypeEnum.OWNERID.getAlias());
                    FieldAttrEntity coUserIdFieldAttr = explainMap.get(FieldTypeEnum.COUSERID.getAlias());
                    if (Objects.isNull(ownerIdFieldAttr) || Objects.isNull(coUserIdFieldAttr) || Objects.equals(ownerIdFieldAttr.getIsOpen(), BasicConstant.ZERO)
                            || Objects.equals(coUserIdFieldAttr.getIsOpen(), BasicConstant.ZERO)) {
                        detailTabPojoIterator.remove();
                    }
                }
            }
        }
    }


}
